package org.jiuling.aliyun.sms;

import com.alibaba.fastjson2.JSON;
import com.aliyun.dysmsapi20170525.Client;
import com.aliyun.dysmsapi20170525.models.SendSmsRequest;
import com.aliyun.dysmsapi20170525.models.SendSmsResponse;
import com.aliyun.teaopenapi.models.Config;
import com.aliyun.teautil.models.RuntimeOptions;
import org.jiuling.aliyun.sms.config.AliYunSmsConfig;
import org.jiuling.aliyun.sms.exception.AliYunSMSRuntimeException;

import java.util.Map;

/**
 * 阿里云短信
 * @author 紫灵
 * @date 2023年01月03日 18时07分32秒
 */
@Deprecated
public class AliYunSms {

    /** 阿里云短信配置 */
    private final AliYunSmsConfig aliYunSmsConfig;

    public AliYunSms(AliYunSmsConfig aliYunSmsConfig) {
        this.aliYunSmsConfig = aliYunSmsConfig;
    }

    /**
     * 创建客户端
     * @return 客户端
     */
    private Client createClient() throws Exception {
        Config config = new Config()
                .setAccessKeyId(aliYunSmsConfig.getAliYunConfig().getAccessKeyId())
                .setAccessKeySecret(aliYunSmsConfig.getAliYunConfig().getAccessKeySecret());
        config.endpoint = aliYunSmsConfig.getServiceAccessPoint().getPublicAccessAddress();
        return new Client(config);
    }

    /**
     * 发送消息
     * @param phoneNumber 手机号
     * @param templateCode 模板代码
     * @param templateParam 模板参数
     */
    public void sendMess(String phoneNumber, String templateCode, Map<String, Object> templateParam){
        try {
            Client client = createClient();
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phoneNumber)
                    .setSignName(aliYunSmsConfig.getSignName())
                    .setTemplateCode(templateCode)
                    .setTemplateParam(JSON.toJSONString(templateParam));
            RuntimeOptions runtimeOptions = new RuntimeOptions();
            SendSmsResponse sendSmsResponse = client.sendSmsWithOptions(sendSmsRequest, runtimeOptions);
            System.out.println(sendSmsResponse.statusCode);
            System.out.println(sendSmsResponse.body.message);
        }catch (Exception e) {
            throw new AliYunSMSRuntimeException(e.getLocalizedMessage());
        }
    }
}
